package cn.broadsense.biz.utils;

import cn.broadsense.common.utils.spring.SpringUtils;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;

import java.util.Date;

/**
 * id生成工具
 *
 * @author: pengxin
 * @create: 2023-09-12 10:59
 * @Version 1.0
 **/
public class IdGenerationUtil {


    /**
     * 生成序号前缀
     */
    private static final String S_NUM_KEY = "v:tags:num:key:%s:%s";

    /**
     * 采集编号
     *
     * @return
     */
    public static String collectionTaskNo() {
        return generate("CJ", 3);
    }

    public static String tagCode() {
        return generate("BJ", 4);
    }

    /**
     * 规则编码
     *
     * @return
     */
    public static String ruleCode() {
        return generate("GZ", 4);
    }

    /**
     * 标签类型编码
     *
     * @return
     */
    public static String typeCode() {
        return generate("BQLX", 4);
    }


    /**
     * 获取值
     *
     * @param prefix
     * @return
     */
    private static String generate(String prefix, int size) {
        Date date = new Date();

        String formatDate = DateUtil.format(date, "yyyyMMdd");
        String key = String.format(S_NUM_KEY, prefix, formatDate);
        //RedisAtomicLong为原子类，根据传入的key和redis链接工厂创建原子类
        RedisAtomicLong counter = new RedisAtomicLong(key, ((RedisTemplate) SpringUtils.getBean("redisTemplate")).getConnectionFactory());
        //设置过期时间 当天结束时间
        DateTime endOfDay = DateUtil.endOfDay(date);
        counter.expireAt(endOfDay);
        //返回redis中key的值
        long seq = counter.incrementAndGet();
        String sequence = StringUtils.leftPad(seq + "", size, "0");
        return prefix + formatDate + sequence;
    }
}
